<?php

namespace app\modules\setting\controllers;

use Yii;
use app\models\Check;
use app\models\CropAvatar;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;

/**
 * CheckController implements the CRUD actions for Check model.
 */
class MediaController extends Controller
{
    public $enableCsrfValidation = false;

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ]
        ];
    }

    /**
     * Lists all Check models.
     * @return mixed
     */
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
                                                   'query' => Check::find(),
                                               ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Check model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $type = Yii::$app->request->get("type", null);
        preg_match('/\d+/', $id, $id);
        return "<img src='./../upload/images/origin/".$type."/".$id[0].".original.jpg' width='800px' />";
    }

    /**
     * @return string
     * @author sally
     * @date   2020-04-28
     */
    public function actionViewMedia()
    {
        $filenames = [];
        $path = scandir("../web/images/upload/media");

        for ($i = 3; $i < count($path); $i ++) {
            $filenames[] = $path[$i];
        }

        return $this->render('index', [
            'view' => 'media',
            'filenames' => $filenames
        ]);
    }

    /**
     * Creates a new Check model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionUpload()
    {
        $pic_name = Yii::$app->request->post('pic-name', null);

        if ($pic_name != null) {

            if ($pic_name == 'media') {
                $pic_name .= '/'.date('YmdHis');
            } else {
                $pic_name .= '/'.Yii::$app->session->get('pt_id');
            }

            $this->checkRepeat($pic_name);

            $crop = new CropAvatar(
                Yii::$app->request->post('avatar_src', null),
                Yii::$app->request->post('avatar_data', null),
                isset($_FILES["avatar_file"]) ? $_FILES["avatar_file"] : null,
                $pic_name
            );

            $response = array(
                'state'  => 200,
                'message' => $crop -> getMsg(),
                'result' => $crop -> getResult()
            );
        } else {

            $response = array(
                'state'  => 404,
                'message' => 'error',
                'result' => 'error'
            );
        }

        return json_encode($response);
    }

    /**
     * Deletes an existing Check model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    protected function checkRepeat($pic_name)
    {
        if (preg_match('/media/', $pic_name)) return ;

        $pic_name .= "/".Yii::$app->session->get('pt_id').".jpg";
        $filepath = "../web/images/upload/";

        if (is_readable($filepath.$pic_name)){
            @unlink($filepath.$pic_name);
            @unlink($filepath."origin/".$pic_name);
        }
    }
}
